#include "webhandler.h"
#include "socketthread.h"
#include "core/coredefine.h"

static WebHandler* web_handler_ = nullptr;

WebHandler* WebHandler::get_instance()
{
    if (nullptr == web_handler_)
        web_handler_ = new WebHandler(nullptr);

    return web_handler_;
}

WebHandler::WebHandler(QObject *parent)
    : QTcpServer(parent)
{
    qDebug() << "Create:" << __FUNCTION__;

    connect(this, &QTcpServer::acceptError, this, [](QAbstractSocket::SocketError err)
    {
        qDebug() << "发生错误 ->" << __FUNCTION__ << __LINE__ << ":\n" << err;
    });
}

void WebHandler::start(quint16 port)
{
    bool ret = listen(QHostAddress::Any, port);
    if (! ret)
    {
        throw std::runtime_error("服务器监听失败");
    }
    else
    {
        qDebug() << "TCP server started on port:" << port;
    }
}

WebHandler::~WebHandler()
{
    DEBUG_FUNC;
}

void WebHandler::incomingConnection(qintptr socketDescriptor)
{
    SocketThread* thread = new SocketThread(socketDescriptor);
    thread->start();
}
